package com.smartleanx.module.hrm.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class FileServiceImpl implements FileService
{
   String region="ap-nanjing";
    /**
     * 初始化
     */
    COSCredentials cred = new BasicCOSCredentials("AKIDPefPt63uhLo3EH8l4B3f1A3mHYaOyJPG", "iCRRL0RdbKp44wxnNhkX3IHzRcXGl00m");

    /**
     *  ClientConfig 区域
     */
    ClientConfig clientConfig = new ClientConfig(new Region(region));
    /**
     *     请求
      */
    COSClient cosClient = new COSClient(cred, clientConfig);


    /**
     *     上传的文件夹及文件地址
     */
     String key = "";



    @Override
    public  String upload(File file){
        String path="";
        try {
            String bucketName = "laoanxin-1326444324";
             path="https://";
            key= LocalDate.now().format(DateTimeFormatter.ofPattern("/yyyyMM/dd/"))+file.getName();
            if(ObjectUtils.isEmpty(bucketName)){
                bucketName=System.currentTimeMillis()+"";
            }
            System.err.println(bucketName+key);

            path+=""+bucketName+".cos."+region+".myqcloud.com"+"/chat"+key;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,"/chat"+key,file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 获取文件的 etag
            String etag = putObjectResult.getETag();
        }catch (Exception e){
            System.err.println(e.getMessage());
        }

        return path;
    }

    public  String uploadUrl(String path) throws IOException {
        URL url = new URL(path);
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        try {
            String bucketName = "laoanxin-1326444324";
             path="https://";
            key= LocalDate.now().format(DateTimeFormatter.ofPattern("/yyyyMM/dd/"))+fileName;
            if(ObjectUtils.isEmpty(bucketName)){
                bucketName=System.currentTimeMillis()+"";
            }
            System.err.println(bucketName+key);

            path+=""+bucketName+".cos."+region+".myqcloud.com"+"/chat"+key;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,"/chat"+key,inputStream,null);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 获取文件的 etag
            String etag = putObjectResult.getETag();
        }catch (Exception e){
            System.err.println(e.getMessage());
        }

        return path;
    }


    public static File transferToFile(MultipartFile multipartFile) {
    // 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0],  "."+filename[1] );
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    /**
     * 测试--------------------------------------------------------------------------------------------------------------------------------------------------------------------
     */
    @Override
    public void createBucket(){
        //存储桶名称，格式：BucketName-APPID
        String bucket = "9999-1307778067";
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
        // 设置 bucket 的权限为 Private(私有读写)、其他可选有 PublicRead（公有读私有写）、PublicReadWrite（公有读写）
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        try{
            Bucket bucketResult = cosClient.createBucket(createBucketRequest);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }
    @Override
    public void  selectBucket(){
        List<Bucket> buckets = cosClient.listBuckets();
        for (Bucket bucketElement : buckets) {
            String bucketName = bucketElement.getName();
            String bucketLocation = bucketElement.getLocation();
            System.err.println("存储桶"+bucketName+","+"存储桶所在地区"+bucketLocation);
        }
    }
    @Override
    public void uploadBucket() {
        // 指定要上传的文件
        File localFile = new File("D:\\mingzhi-saas\\pom.xml");
        // 指定文件将要存放的存储桶
        String bucketName = "9999-1307778067";
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = "test";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        System.err.println(putObjectResult);
    }

    @Override
    public String uploadSoundRecording(File file) {
        String path="";
        try {
            String bucketName = "soundrecording-1307778067";
            path="https://";
            key= LocalDate.now().format(DateTimeFormatter.ofPattern("/yyyyMM/dd/"))+file.getName();
            if(ObjectUtils.isEmpty(bucketName)){
                bucketName=System.currentTimeMillis()+"";
            }
            System.err.println(bucketName+key);

            path+=""+bucketName+".cos."+region+".myqcloud.com"+"/soundrecording"+key;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,"/soundrecording"+key,file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 获取文件的 etag
            String etag = putObjectResult.getETag();
        }catch (Exception e){
            System.err.println(e.getMessage());
        }

        return path;
    }



}
